/*
 * usb_data_transfer.c
 *
 *  Created on: Sep 23, 2023
 *      Author: colourfate
 */
#include "usb_data_transfer.h"
#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "usb_conf.h"
#include "usb_core.h"
#include "usbd_int.h"
#include "cdc_class.h"
#include "cdc_desc.h"
#define DATA_EOF_LEN  2
#define USB_DATA_HEAD 0x8000

ALIGNED_HEAD uint8_t usb_buffer[256] ALIGNED_TAIL;
uint8_t g_receive_ok = 0;
usb_control_cmd g_usb_cmd;

uint16_t data_len;
extern otg_core_type otg_core_struct;
void receive_data_parse()
{
    data_len = usb_vcp_get_rxdata(&otg_core_struct.dev, usb_buffer);
    if (data_len >= 7) {
        if (((usb_buffer[1] << 8) | usb_buffer[0]) == USB_DATA_HEAD && ((usb_buffer[3] << 8) | usb_buffer[2]) >= USB_DATA_TYPE_MAX && ((usb_buffer[5] << 8) | usb_buffer[4]) != 0) {
            memset(&g_usb_cmd, 0, sizeof(usb_control_cmd));
            if (((usb_buffer[3] << 8) | usb_buffer[2]) == USB_DATA_TYPE_CMD_FPS && ((usb_buffer[5] << 8) | usb_buffer[4]) == 1) {
                g_usb_cmd.fps = usb_buffer[6];
                g_receive_ok  = 1;
            } else {
                return;
            }
        }
    }
}
uint8_t char_cache[768 * 2 + 6];
int usb_data_store_f(float *data)
{
    // uint32_t packet_len = 768 * 2 + 6;
    uint32_t i;

    // usb_data_format *g_packet = (usb_data_format *)g_usb_tx_buffer;
    // memset(g_usb_tx_buffer, 0, packet_len);

    // for (i = 0; i < data_len; i++) {
    //     *((uint16_t *)(&g_packet->data[2 * i])) = (uint16_t)(data[i] * 100);
    // }
    // memset(char_cache, 0, packet_len);
    *((uint16_t *)(char_cache))     = USB_DATA_HEAD;
    *((uint16_t *)(char_cache + 2)) = USB_DATA_TYPE_DATA;
    *((uint16_t *)(char_cache + 4)) = (uint16_t)(768 * 2);
    for (i = 0; i < 768; i++) {
        *((uint16_t *)(char_cache + i * 2 + 6)) = (uint16_t)(data[i] * 100);
    }

    return 0;
}

int timeout = 0;
void usb_data_send(void)
{
    // uint32_t start;

    /// start = HAL_GetTick();
    // while (CDC_Transmit_FS((uint8_t *)g_packet, g_packet->len + sizeof(usb_data_format)) != USBD_OK);
    // pinfo("send data: %ld\r\n", HAL_GetTick() - start);
    timeout = 5000000;
    do {
        /* send data to host */
        if (usb_vcp_send_data(&otg_core_struct.dev, char_cache, 768 * 2 + 6) == SUCCESS) {
            break;
        }
    } while (timeout--);
}

int usb_get_cmd(usb_control_cmd *cmd)
{
    if (cmd == NULL) {
        printf("Param is NULL\r\n");
        return -1;
    }

    if (g_receive_ok == 0) {
        return 0;
    }

    *cmd         = g_usb_cmd;
    g_receive_ok = 0;
    return 1;
}
